<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2021/08/23
 * Time: 23:53
 * @link http://www.lmterp.cn
 */

namespace app\common\model;

/**
 * 物流属性
 * Class ChannelAttr
 * @package app\common\model
 */
class ChannelAttr extends BaseModel
{
    protected $pk = 'attr_id';

    protected $autoWriteTimestamp = 'datetime';

    protected $insert = ['create_by', 'update_by'];

    protected $update = ['update_by'];

    /**
     * 关联商品
     * @return \think\model\relation\BelongsToMany
     * @date 2021/08/25
     * @author longli
     */
    public function product()
    {
        return $this->belongsToMany(Product::class, ProductLogisticsAttr::class, 'product_id', 'attr_id');
    }

    /**
     * 通过商品SKU 获取商品物流属性
     * @param string|array $sku SKU
     * @return array
     * @date 2021/08/29
     * @author longli
     */
    public static function getCattrBySku($sku)
    {
        $attrs = [];
        $products = Product::with(["cattrs"])->whereIn("product_id", function($query) use($sku)
        {
            $query->table(ProductStore::getTable())->whereIn("sku", $sku)->field("product_id");
        })->select();
        foreach($products as $product)
        {
            $attrs = array_merge($attrs, array_column($product->cattrs->toArray(), 'attr_id'));
        }
        return array_unique($attrs);
    }

    /**
     * 通过物流属性id 获取名称或者编号
     * @param string|array $ids 属性id
     * @param string $field 可选值，attr_name, code 默认 attr_name
     * @return array
     * @date 2021/09/02
     * @author longli
     */
    public static function getNameByIds($ids, $field = 'attr_name')
    {
        return static::whereIn("attr_id", $ids)->column($field);
    }
}
